/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-plusplus */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable no-template-curly-in-string */
// 批量管理
import { DatabaseFilled } from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  Descriptions,
  Divider,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Spin,
  Steps,
  Table,
  Tag,
} from 'antd';
import React, { useState } from 'react';
import type {
  DeviceIdGetArrParamsType,
  DeviceControlParamsType,
  SpreadingGoodsSeller} from '@/services/device';
import {
  DeviceIdGetArr,
  DeviceIdBatchUnbinding,
  DeviceIdBulkBindingAdd,
  getSpreadingGoodsSeller,
  adminBulkBindingSubordinateList,
  AdminBulkUnbindingProxy,
  AdminBulkBindingProxy,
  AdminDeviceIdGetArr,
} from '@/services/device';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from 'umi';
import { connect } from 'umi';
import type { ColumnsType } from 'antd/lib/table';

const validateMessages = {
  required: '${label}未设置!',
};

interface ManageProps {
  userState?: CurrentUser;
  updateData?: Function;
  title?: string; // 标题
  type?: number; // 类型 1-商户 2-代理
}

type DeviceItem = {
  num: string;
  isBind: boolean;
};

type SellerItem = {
  id: number;
  name: string;
};

type DelegateItem = {
  id: number;
  name: string;
  type: number;
};

const Manage: React.FC<ManageProps> = (props) => {
  const { userState, title, type } = props;
  const [show, setShow] = useState(false);
  const [loading, setLoading] = useState(false);
  const [devicesGet, setDevicesGet] = useState<DeviceItem[]>([]);
  const [seller, setSeller] = useState<SellerItem[]>([]);
  const [delegate, setDelegate] = useState<DelegateItem[]>([]);
  const [chooseSeller, setChooseSeller] = useState<SellerItem | null>(null);
  const [chooseDelegate, setChooseDelegate] = useState<DelegateItem | null>(null);
  const [current, setCurrent] = useState(0);
  const [search, setSearch] = useState(''); // 商户搜索

  const deleteItem = (row: DeviceItem) => {
    const index = devicesGet.findIndex((item) => item.num === row.num);
    devicesGet.splice(index, 1);
    setDevicesGet([...devicesGet]);
  };

  // 表格列表
  const columns: ColumnsType<DeviceItem> = [
    {
      title: '设备编号',
      dataIndex: 'num',
      key: 'num',
    },
    {
      title: '设备状态',
      dataIndex: 'isBind',
      render: (isBind) => {
        if (isBind) {
          if (type === 1) {
            return <Tag color="geekblue">已铺货</Tag>;
          } 
            return <Tag color="geekblue">已绑定代理</Tag>;
          
        } if (type === 1) {
            return <Tag color="red">未铺货</Tag>;
          } 
            return <Tag color="red">未绑定代理</Tag>;
          
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, row) => {
        return <a onClick={() => deleteItem(row)}>删除</a>;
      },
    },
  ];

  // 商户列表
  const sellerColumns: ColumnsType<SellerItem> = [
    {
      title: '商户Id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '商户名称',
      dataIndex: 'name',
    },
    {
      title: '选择',
      dataIndex: 'operation',
      render: (_, row) => {
        return (
          <Radio
            key={row.id}
            checked={!!(chooseSeller && chooseSeller.id === row.id)}
            onClick={() => setChooseSeller(row)}
          >
            {chooseSeller && chooseSeller.id === row.id ? '选择' : '未选中'}
          </Radio>
        );
      },
    },
  ];

  const delegateColumns: ColumnsType<DelegateItem> = [
    {
      title: '代理Id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '代理名称',
      dataIndex: 'name',
    },
    {
      title: '代理类型',
      dataIndex: 'type',
      render: (type) => {
        if (type === 1) return <Tag color="geekblue">业务代理</Tag>;
        if (type === 2) return <Tag color="yellow">区域代理</Tag>;
        if (type === 3) return <Tag color="purple">市级代理</Tag>;
        if (type === 4) return <Tag color="red">省级代理</Tag>;
        return <Tag color="valcano">店铺代理</Tag>;
      },
    },
    {
      title: '选择',
      dataIndex: 'operation',
      render: (_, row) => {
        return (
          <Radio
            key={row.id}
            checked={!!(chooseDelegate && chooseDelegate.id === row.id)}
            onClick={() => setChooseDelegate(row)}
          >
            {chooseDelegate && chooseDelegate.id === row.id ? '选择' : '未选中'}
          </Radio>
        );
      },
    },
  ];

  // 获取设备
  const onFinish = async (values: any) => {
    // console.log(values);
    setLoading(true);
    const data: DeviceIdGetArrParamsType = {
      uId: userState?.id!,
      userType: userState?.user_type!,
      token: userState?.token!,
      type: 2,
      startCabinetId: values.startCabinetId,
      endCabinetId: values.endCabinetId,
    };
    try {
      let res;
      if (type === 1) {
        res = await DeviceIdGetArr(data);
      } else {
        res = await AdminDeviceIdGetArr(data);
      }

      // console.log(res);
      if (res.code === 0) {
        // 处理数据
        // 处理为绑定
        const devices = [];
        if (res.data.not && res.data.not.length > 0) {
          // 处理未绑定设备
          for (let i = 0; i < res.data.not.length; i++) {
            const num = res.data.not[i];
            devices.push({
              num,
              isBind: false,
            });
          }
        }
        if (res.data.Bound && res.data.Bound.length > 0) {
          // 处理未绑定设备
          for (let i = 0; i < res.data.Bound.length; i++) {
            const num = res.data.Bound[i];
            devices.push({
              num,
              isBind: true,
            });
          }
        }
        setDevicesGet(devices);
      } else {
        message.error(res.msg);
      }
    } catch (err) {
      message.error('请求失败，请重试!');
    }
    setLoading(false);
  };

  // 切换到商户
  const changeToSeller = (current: number) => {
    if (current === 1) {
      if (devicesGet.length <= 0) {
        message.info('请先选择设备!');
        return;
      }
      getSeller();
    }
    setCurrent(current);
  };

  // 解绑
  const unbindDevice = async () => {
    if (devicesGet.length <= 0) {
      message.info('请先选择设备!');
      return;
    }
    setLoading(true);

    const cabinet = devicesGet.map((item) => item.num);
    const data: DeviceControlParamsType = {
      uId: userState?.id!,
      userType: userState?.user_type!,
      token: userState?.token!,
      type: 2,
      cabinetId: cabinet,
    };

    try {
      let res;
      if (type === 1) {
        res = await DeviceIdBatchUnbinding(data);
      } else if (type === 2) {
        res = await AdminBulkUnbindingProxy(data);
      }
      if (res.code === 0) {
        message.success(res.data);
        setDevicesGet([]);
        if (props.updateData) {
          props.updateData();
        }
      } else {
        message.error(res.msg);
      }
    } catch (err) {
      message.error('解绑失败,请重试!');
    }

    setLoading(false);
  };

  // 下一步选择商户
  const toNext = () => {
    if (devicesGet.length <= 0) {
      message.info('请先选择设备!');
      return;
    }
    setCurrent(1);
    getSeller();
  };

  // 获取可铺货商户
  const getSeller = async () => {
    setLoading(true);

    const data: SpreadingGoodsSeller = {
      uId: userState?.id!,
      userType: userState?.user_type!,
      token: userState?.token!,
      select: search,
    };
    setChooseSeller(null);
    setChooseDelegate(null);
    try {
      let res;
      if (type === 1) {
        // 获取商户列表
        res = await getSpreadingGoodsSeller(data);
        if (res.code === 0) {
          setSeller(res.data);
        } else {
          message.error(res.msg);
          setCurrent(0);
        }
      } else {
        // 获取代理列表
        res = await adminBulkBindingSubordinateList(data);
        if (res.code === 0) {
          setDelegate(res.data);
        } else {
          message.error(res.msg);
          setCurrent(0);
        }
      }
    } catch (err) {
      setCurrent(0);
      message.error('获取失败,请重试!');
    }

    setLoading(false);
  };

  // 修改输入框
  const onChange = (event: any) => {
    event.persist();
    if (event && event.target && event.target.value) {
      const {value} = event.target.value;
      setSearch(value);
    }
  };

  // 绑定商户
  const bindDevice = async () => {
    if (type === 1) {
      if (!chooseSeller) {
        message.info('请先选择绑定商户!');
        return;
      }
    } else if (type === 2) {
      if (!chooseDelegate) {
        message.info('请先选择绑代理!');
        return;
      }
    }

    setLoading(true);

    const cabinet = devicesGet.map((item) => item.num);
    let data: DeviceControlParamsType;
    try {
      let res;
      if (type === 1 && chooseSeller) {
        data = {
          uId: userState?.id!,
          userType: userState?.user_type!,
          token: userState?.token!,
          type: 2,
          cabinetId: cabinet,
          sId: chooseSeller.id!,
        };
        res = await DeviceIdBulkBindingAdd(data);
      } else if (chooseDelegate) {
        data = {
          uId: userState?.id!,
          userType: userState?.user_type!,
          token: userState?.token!,
          type: 2,
          cabinetId: cabinet,
          aId: chooseDelegate.id!,
        };
        // console.log(chooseDelegate);
        res = await AdminBulkBindingProxy(data);
      }

      if (res.code === 0) {
        message.success(res.data);
        setChooseSeller(null);
        setChooseDelegate(null);
        setDevicesGet([]);
        setSeller([]);
        setCurrent(0);
        if (props.updateData) {
          props.updateData();
        }
      } else {
        message.error(res.msg);
      }
    } catch (err) {
      message.error('绑定失败,请重试!');
    }

    setLoading(false);
  };

  return (
    <>
      {type === 1 ? (
        <Button key="button" icon={<DatabaseFilled />} type="primary" onClick={() => setShow(true)}>
          {title || '批量操作(商户)'}
        </Button>
      ) : (
        <Button
          key="button"
          icon={<DatabaseFilled />}
          type="primary"
          onClick={() => setShow(true)}
          danger
        >
          {title || '批量操作(商户)'}
        </Button>
      )}

      <Modal
        visible={show}
        footer={null}
        width={600}
        // onOk={this.handleOk}
        onCancel={() => setShow(false)}
      >
        <Spin spinning={loading}>
          <Steps
            style={{ marginTop: 30 }}
            current={current}
            onChange={(current) => changeToSeller(current)}
          >
            <Steps.Step title="获取操作设备"></Steps.Step>
            <Steps.Step title={type === 1 ? '选择绑定商户' : '选择绑定代理'}></Steps.Step>
          </Steps>
          <Divider></Divider>
          {current === 0 ? (
            <Card title="获取设备">
              <Form onFinish={onFinish} validateMessages={validateMessages}>
                <Form.Item
                  name="startCabinetId"
                  label="起始设备编号"
                  rules={[{ required: true, message: '请输入起始设备编号!' }]}
                >
                  <Input placeholder="请输入起始设备编号" />
                </Form.Item>
                <Form.Item
                  name="endCabinetId"
                  label="起始设备编号"
                  rules={[{ required: true, message: '请输入结束设备编号!' }]}
                >
                  <Input placeholder="请输入结束设备编号" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    获取设备
                  </Button>
                </Form.Item>
              </Form>
              {/* 设备数量 */}
              <Descriptions>
                <Descriptions.Item label="获取设备数量:">{devicesGet.length}</Descriptions.Item>
              </Descriptions>
              {/* 设备列表 */}
              <Table
                dataSource={devicesGet}
                columns={columns}
                scroll={{ x: 'max-content', y: 260 }}
                rowKey={(columns) => columns.num}
              ></Table>
              {/* 底部按钮 */}
              <div style={{ marginTop: 20 }}>
                <Button style={{ marginRight: 8 }} type="primary" onClick={() => toNext()}>
                  绑定设备
                </Button>
                <Button danger onClick={() => unbindDevice()}>
                  解绑设备
                </Button>
              </div>
            </Card>
          ) : (
            //   商户列表
            <Card title={type === 1 ? '商户列表' : '代理列表'}>
              {/* 搜索 */}
              <Row style={{ marginBottom: 16 }}>
                <Col>
                  <Input
                    placeholder={type === 1 ? '请输入搜索商户名称' : '请输入搜索代理名称'}
                    // value={search}
                    onChange={onChange}
                  ></Input>
                </Col>
                <Col style={{ marginLeft: 8 }}>
                  <Button onClick={() => getSeller()}>搜索</Button>
                </Col>
              </Row>
              {/* 设备列表 */}
              {type === 1 ? (
                <Table
                  dataSource={seller}
                  columns={sellerColumns}
                  scroll={{ x: 'max-content', y: 260 }}
                  rowKey={(columns) => columns.id}
                ></Table>
              ) : (
                <Table
                  dataSource={delegate}
                  columns={delegateColumns}
                  scroll={{ x: 'max-content', y: 260 }}
                  rowKey={(columns) => columns.id}
                ></Table>
              )}
              {/* 底部按钮 */}
              <div style={{ marginTop: 20 }}>
                <Button style={{ marginRight: 8 }} type="primary" onClick={() => bindDevice()}>
                  确认
                </Button>
              </div>
            </Card>
          )}
        </Spin>
      </Modal>
    </>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(Manage);
